package com.tinem.platform.service.graphql.controller;

import com.tinem.platform.service.graphql.jpa.GraphQLExecutor;
import graphql.ExecutionResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/")
class GraphQlController {

    @Autowired
    private GraphQLExecutor graphQLExecutor;

    @RequestMapping(path = "/graphql.api", method = RequestMethod.POST)
    public ExecutionResult graphQl(@RequestBody final GraphQLInputQuery query) throws IOException {
        Map<String, Object> variables = query.getVariables() != null ? query.getVariables() : null;

        return graphQLExecutor.execute(query.getQuery(), variables);
    }

    @Data
    public static final class GraphQLInputQuery {
        String query;
        Map variables;
    }

}